#coding=utf8
import socket, threading
from ws_setting import logger, address, port, max_connections, CUSTOM_OBJ_SESSION_ID_NAME
from core.session import Session

class Connector():
    def __init__(self):
        pass

    def init_server(self, container):
        self.container = container

        server = socket.socket()
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((address, port))
        server.listen(max_connections)
        self.server = server

        self.container.initialization()

        run_forver(self)



def executor(session):
    while not session.closed:
        session.process()
    logger.debug("detected session should be closed")
    session.close_session()


def run_forver(connector):
    while True:
        try:
            conn, addr = connector.server.accept()
            try:
                session = Session(conn, connector.container, *addr)
                threading.Thread(target=executor, args=(session,), name="connector execute (%s)" % getattr(session, CUSTOM_OBJ_SESSION_ID_NAME)).start()
            except:
                import traceback
                logger.error(traceback.print_exc())

        except KeyboardInterrupt:
            connector.container.clean()
            connector.container.ws_application = None
            connector.server.close()
            import sys
            sys.exit(1)
            #os.close()
            logger.debug("force to exit")

